package com.woniuxy.sales.controller;

import com.qiniu.util.Auth;
import com.woniuxy.sales.common.RedisConst;
import com.woniuxy.sales.common.enumeration.BusinessCode;
import com.woniuxy.sales.common.enumeration.Constant;
import com.woniuxy.sales.model.dto.SubmitAppointments;
import com.woniuxy.sales.model.vo.AppointmentsVo;
import com.woniuxy.sales.service.AppointmentsService;
import com.woniuxy.sales.untils.Assert;
import com.woniuxy.sales.untils.JwtTemplate;
import com.woniuxy.sales.untils.QiNiuUploadUtils;
import com.woniuxy.sales.untils.SmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.List;


@RestController
@RequestMapping("/appointments")
@Api(tags = "预约订单接口")
@Slf4j
public class AppointmentsController {
    @Autowired
    private AppointmentsService appointmentsService;
    @Autowired
    private JwtTemplate jwtTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SmsUtil smsUtil;

    @GetMapping("/query")
    @ApiOperation("查询所有预约订单")
    public ResponseEntity query(
            @RequestHeader(name = "Authorization", required = false) String token) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        log.info("用户id:{}", userId);
        //调用业务层查询订单
        List<AppointmentsVo> appointmentsVos = appointmentsService.query(userId);
        log.info("预约订单信息:{}", appointmentsVos);
        return ResponseEntity.ok(appointmentsVos);
    }

    @GetMapping("/queryByStatus")
    @ApiOperation("查询指定状态的订单")
    public ResponseEntity queryByStatus(@RequestHeader(name = "Authorization", required = false) String token,
                                        Integer status) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        log.info("用户id:{}", userId);
        //调用业务层查询订单
        List<AppointmentsVo> appointmentsVos = appointmentsService.queryByStatus(userId, status);
        log.info("预约订单信息:{}", appointmentsVos);
        return ResponseEntity.ok(appointmentsVos);
    }

    @DeleteMapping("/remove/{id}")
    @ApiOperation("删除预约订单")
    public ResponseEntity remove(@PathVariable Integer id) {
        appointmentsService.remove(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/updateStatus/{appointmentId}")
    public ResponseEntity<String> updateStatus(@PathVariable Long appointmentId) {
        try {
            boolean isUpdated = appointmentsService.updateStatusToExpired(appointmentId);
            if (isUpdated) {
                return ResponseEntity.ok("状态更新成功");
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("预约未找到或已是已过期状态");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新状态失败");
        }
    }

    @PostMapping("/submit")
    @ApiOperation("提交预约订单")
    public ResponseEntity<?> smsLogin(@RequestHeader(name = "Authorization", required = false) String token,
            @RequestBody SubmitAppointments params) {
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        String telephone = params.getTelephone();
        String codeKey = RedisConst.SHORT_MESSAGE_SERVICE + ":" + telephone;
        String smsCode = stringRedisTemplate.opsForValue().get(codeKey);
        Assert.error(! StringUtils.hasText(smsCode), BusinessCode.INVALID_VERIFICATION);
        String code = params.getCode();
        Assert.error(! code.equals(smsCode), BusinessCode.VERIFICATION_ERROR);
        stringRedisTemplate.delete(codeKey);

        appointmentsService.submit(userId,params);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/sendSms")
    @ApiOperation("手机号发短信")
    public ResponseEntity<String> sendSms(@RequestBody SubmitAppointments params) {
        String telephone = params.getTelephone();
        String name=params.getName();

        String smsContent = "您已成功预约，请等待客服电话联系";

        if (name != null && !name.trim().isEmpty()) {
            smsContent = "尊敬的 " + name + "您已成功预约，请等待客服电话联系";
        }

        //String result = smsUtil.sendSms(telephone, smsContent);
        String result="OK";
        Assert.error(!result.equals("OK"), BusinessCode.SMS_SEND_ERROR);
        String response = smsContent+"手机号：" + maskPhoneNumber(telephone);
        return ResponseEntity.ok(response);
    }

    private String maskPhoneNumber(String phone) {
        // 将第4、5、6、7位替换为 *
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }


}